package com.garvin.jwt;

import org.springframework.util.Base64Utils;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author : garvin
 * @version V1.0
 * @date : 2020年05月20日 10:32
 */
public final class KeyGeneratorUtil {
    private KeyGeneratorUtil() {
    }

    public static KeyPairStr getKeyPairStr(String algorithm) throws Exception {
        KeyPair keyPair = getKeyPair(algorithm);
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        String publicKeyStr = Base64Utils.encodeToString(publicKey.getEncoded());
        String privateKeyStr = Base64Utils.encodeToString(privateKey.getEncoded());
        return new KeyPairStr(publicKeyStr, privateKeyStr);
    }

    public static KeyPair getKeyPair(String algorithm) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }

    public static void main(String[] args) throws Exception {
        KeyPairStr keyPair = KeyGeneratorUtil.getKeyPairStr("RSA");
        System.out.println(keyPair.getPublicKey());
        System.out.println(keyPair.getPrivateKey());
    }
}
